import {
  AfterContentInit,
  AfterViewInit,
  Component,
  ComponentFactoryResolver,
  ElementRef,
  HostBinding,
  OnInit,
  SimpleChanges,
  ViewChild,
  ViewContainerRef,
} from '@angular/core';
import * as moment from 'moment';
// tslint:disable-next-line:import-blacklist
import { combineLatest } from 'rxjs';
import { CaseReviewService } from '../../../../@core/service/case-review/case-review.service';
import { DocgenService } from '../../../../@core/service/case-review/doc-select/api/docgen.service';
import { BizfileService } from '../../../../@core/service/case-review/doc-service/api/bizfile.service';
import { CaseService } from '../../../../@core/service/handle-service/api/case.service';
import { CaseDocService } from '../../../../@core/service/handle-service/api/caseDoc.service';
import { 
  components as Coms,
  importComs,
} from '../../../common/doc-module/comDoc';
// 接口规范
import { ReturnCaseCode } from '../../../../@core/service/handle-service';
import { ReturnModel } from '../../../../@core/service/evidence';
import { StakeHolderService } from '../../../../@core/service/handle-service/api/stakeHolder.service';
import { SYSTEMService } from '../../../../@core/service/login-service/api/sYSTEM.service';
import { NzMessageService } from 'ng-zorro-antd/message';

// 审批组件
@Component({
  selector: 'app-casereview',
  templateUrl: './casereview.component.html',
  styleUrls: ['./casereview.component.scss'],
  // entryComponents:[...importComs],
})
export class CasereviewComponent implements OnInit {
  // 获取loadContainer
  @ViewChild('loadContainer', { read: ViewContainerRef })container: ViewContainerRef;
  // 加载动画
  public loadSpin:boolean=true; 

  public formJson: any = {};  //// formJson
  // 请求数据
  public filedata: any = {data: {stage: null}};

  // caseModule审批select
  public caseModule: [];       // filedata[1]
  public docid: string;        // docid审批传递值
  public doctype: string;      // 文书名称
  public condition: any;       // 新增or审批条件
  public bizid: string;        // 业务id
  public loading: boolean;     // 加载缓存值
  public com: any;             // 当前组件
  public comRef: any;          // 当前组件视图
  // 审批模块参数
  public approvalModule: any = {
    caseradioName: null,      // 审批意见name
    caseradioValue: null,     // 审批意见radio枚举（0 = 同意 ,1 = 不同意 ,2 驳回）
    caseModuleValue: null,    // 审批模块select框
    ideaValue: null,          // 审批意见
    date: null,               // 审批时间
  };
  public callback: any;       // 父组件回调刷新文书列表方法

  public caseType: any;       // 案件环节
  approvalArr: any;           // 请求接口返回数据缓存 filedata[0] 获取当前审批文书信息    filedata[1]获取当前文书select列表  filedata[2]查询当前文书回显数据
  constructor(
    private el: ElementRef,                           // 导入当前元素组件
    private resolver: ComponentFactoryResolver,       // 导入组件生产工厂
    public caseReview: CaseReviewService,             // 审批模块serivce导入
    public bizfile: BizfileService,                   // 文书service导入（孙·飞）
    public docgen: DocgenService,                     // 文书service导入 (志·敏)
    public caseservice: CaseService,                  // 审批案件service导入 (文·超)
    public stake:StakeHolderService,                  // 根据案件id获取办案人员
    public user:SYSTEMService,
    public message:NzMessageService,
    public caseDocService:CaseDocService              // 新增 修改 审批 调用文书接口
  ) {}
ngOnInit() {
  let that = this;
  // 动态计算弹框大小
  const h = document.documentElement.clientHeight || document.body.clientHeight;
  this.el.nativeElement.style.height = h - 35 + `px`;
  // modalContent
  // 传递full-staff组件点击参数
  this.caseReview.getCreateCaseDoc().subscribe(({ condition, docid, doctype, bizid, callback}) => {
    this.loadSpin = true;
    this.approvalModule.caseradioName  = null;      // 审批意见name
    this.approvalModule.caseradioValue  = null;     // 审批意见radio枚举 （0 = 同意 ,1 = 不同意 ,2 驳回）
    this.approvalModule.caseModuleValue  = null;    // 审批模块审批select选择值
    this.approvalModule.ideaValue  = null;          // 审批模块审批意见初始化
    this.approvalModule.date  = null;               // 审批模块中日期初始化
    this.caseType = null;                           // 文书类型初始化
    this.filedata.data.stage = null;                // 文书环节初始化
      // 初始化container容器
    if (this.container) { this.container.clear(); }
    
    this.callback = callback;   // callback 刷新文书列表
    this.condition = condition; // 判断条件
    this.doctype = doctype;     // 当前文书type
    this.bizid = bizid;         // 当前业务id
    this.docid = docid;         // 当前文书id
    const el = this.findElement(this.el.nativeElement, 'modalContent');

    let  approvalFn = function(){ 
      if (that.container && that.container.clear) {
           that.container.clear();
         }
         that.comRef = that.container.createComponent(that.com);
          if (that.docid) { that.comRef.instance.docid = that.docid;}
          if(doctype == '案件来源登记表'||doctype == '立案审批表'||doctype == '不予立案审批表'){
            that.comRef.instance.treeValue =  that.approvalArr[2].data.caseType;
            that.caseType = that.approvalArr[2].data.caseType;
          }
          that.comRef.instance.isReadonly = true;
          that.comRef.instance.loadSpin.subscribe((res) => {
            that.loadSpin = false; //修改登陆加载状态
          },()=>null,()=>{
            that.comRef.instance.loadSpin.unsubscribe()
          });
    };

//  ************************审批查看文书************************
      // 判断是否为审批,否则为新增
    if (condition === 'Approval' || condition === 'See') {
      // 计算高度modalContent
      if(condition ==='Approval'){
        el[0].style.height = this.el.nativeElement.style.height.match(/\d+/)[0] - 177 - 96 + `px`;
      }else{
        el[0].style.height = this.el.nativeElement.style.height.match(/\d+/)[0] -96  + `px`;
      }
      // 调用方法请求数据
        combineLatest(
          this.bizfile.queryBizFileByDocid(docid),
          this.docgen.docgenApprovalTypeGet(doctype),
          this.caseservice.caseIdIdGet(this.bizid),
          ).subscribe((filedata: any) => {
              this.approvalArr = filedata;
      // filedata[0] 获取当前审批文书信息    filedata[1]获取当前文书select列表  filedata[2]查询当前文书回显数据
      // 获取filedata[0]数据(emit数据)
              this.filedata = filedata[0];
      // 获取服务返回数据
              this.caseModule = filedata[1]; 
      // 判断审批表单
              switch (doctype) {
      // 案件来源登记表 （审批）
              case '案件来源登记表':
      // 调用查询案件信息返回赋值
                    this.com = this.resolver.resolveComponentFactory(Coms['ClueSourceComponent']);
                    console.log(this.com)
                    if (this.container && this.container.clear) {
                    this.container.clear();
                    this.comRef = this.container.createComponent(this.com);
                    this.loadSpin = false; //修改登陆加载状态
                    this.comRef.instance.formJson = this.formJson = JSON.parse(this.approvalArr[0]['data']['formJson']);
                    this.comRef.instance.treeValue  =  this.approvalArr[2].data.caseType;
                    this.caseType = this.approvalArr[2].data.caseType;
                }
                    break;
      // 立案审批表 （审批）
              case '立案审批表':
                  this.com = this.resolver.resolveComponentFactory(Coms['RegisterApprovalComponent'] );
                  approvalFn();
                  break;
     // 不予立案审批表 （审批）
              case '不予立案审批表':
                  this.com = this.resolver.resolveComponentFactory(Coms['RegisterNoApprovalComponent'] );
                  approvalFn();
                  break;
     //结案审批表
              case '结案审批表':
                this.com = this.resolver.resolveComponentFactory(Coms['ClosingApprovalComponent'] );
                approvalFn();
                break;
     //行政处罚案件有关事项审批表
              case '行政处罚案件有关事项审批表':
                this.com = this.resolver.resolveComponentFactory(Coms['RelatedMattersComponent'] );
                approvalFn();
                break;
     //行政处理决定审批表
              case '行政处理决定审批表':
                  this.com = this.resolver.resolveComponentFactory(Coms['DecisionApprovalFromComponent'] );
                  approvalFn();
                  break;
     //案件审核表
              case '案件审核表':
                  this.com = this.resolver.resolveComponentFactory(Coms['CaseReviewFormComponent'] );
                  approvalFn();
                  break;
     //案件调查终结报告
              case '案件调查终结报告':
                  this.com = this.resolver.resolveComponentFactory(Coms['TerminationReportComponent'] );
                  approvalFn();
                  break;
     //指定管辖通知书
              case '指定管辖通知书':
                this.com = this.resolver.resolveComponentFactory(Coms['JurusductionNoticeComponent'] );
                approvalFn();
                break;
     //《案件移送函》
              case '案件移送函':
                this.com = this.resolver.resolveComponentFactory(Coms['CaseTransferLetterComponent'] );
                approvalFn();
                break;
     // 案件交办通知书           
              case '案件交办通知书':
                this.com = this.resolver.resolveComponentFactory(Coms['CaseFilingNoticeComponent'] );
                approvalFn();
              break;
     // 涉嫌犯罪案件移送书         
              case '涉嫌犯罪案件移送书':
                this.com = this.resolver.resolveComponentFactory(Coms['CriminalCaseTransferLetterComponent'] );
                approvalFn();
              break;
     //协助调查函
              case '协助调查函':
                this.com = this.resolver.resolveComponentFactory(Coms['InverstigationLetterComponent'] );
                approvalFn();
                break;
     //协助扣押通知书
              case '协助扣押通知书':
                this.com = this.resolver.resolveComponentFactory(Coms['ArrestNoticeComponent'] );
                approvalFn();
                break;
     //other模块处理 (审批)
              default:
                  this.com = this.resolver.resolveComponentFactory(Coms['OtherComponent']);
                  if (this.container && this.container.clear) {
                    this.container.clear();
                    this.comRef = this.container.createComponent(this.com);
                  }
                  break;
            }
                    this.comRef.instance.bizid = this.bizid;
        },(err)=>null,()=>{

        });
// ************************新增文书************************          
    } else if (condition === 'New') {
      // 新增时取办案人员
      // authLoginUserUserId
      let caseHandler=(str)=>{
        this.stake.stakeHolderTargetCaseIdGet(this.bizid).subscribe((data:any)=>{
          if(data['rel']){
            let userIdArr:any[] = [];
            for(let i = 0;i<data['data'].length;i++){
              this.user.authBaseUserUserIdGet(data['data'][i]['targetUserId']).subscribe((succ:any)=>{
                let exeperHtml ="";
                userIdArr.push(succ['data']); 
                if(i==data['data'].length-1){
                  //赋值
                  if(doctype =="案件调查终结报告"){
                    this.comRef.instance.formJson.cNa =  userIdArr[0]['realName']
                    this.comRef.instance.formJson.cNa2 = userIdArr[1]['realName']
                  }else{
                    for(let i = 0;i<userIdArr.length;i++){
                      if(i == 0){
                        exeperHtml = userIdArr[i]['realName']
                      }else{
                        exeperHtml+='，'+userIdArr[i]['realName']
                      }
                    }
                    this.comRef.instance.formJson[str] = exeperHtml
                  }
                }
                
              })
            }
          }
        })
      }
   this.loadSpin = false; //修改登陆加载状态  
          // tslint:disable-next-line: prefer-const
  // 如果是编辑则调用方法传回参数
          // 计算高度modalContent
          el[0].style.height = h - 130 + `px`;
  // 初始化所有登记表信息组件;
            // 判断审批表单
          switch (doctype) {
  // 立案审批表 （新增  编辑）
            case '立案审批表':
              this.com = this.resolver.resolveComponentFactory(Coms['RegisterApprovalComponent'] );
              break;
  // 不予立案审批表（新增  编辑）
            case '不予立案审批表':
              this.com = this.resolver.resolveComponentFactory(Coms['RegisterNoApprovalComponent'] );
              break;
  // 结案审批表（新增  编辑）
            case '结案审批表':
              this.com = this.resolver.resolveComponentFactory(Coms['ClosingApprovalComponent'] );
              caseHandler('exeper') //取办案人员
              break;
  // 行政处理决定审批表（新增  编辑）
            case '行政处罚案件有关事项审批表':
                this.com = this.resolver.resolveComponentFactory(Coms['RelatedMattersComponent'] );
                caseHandler('casePerson') //取办案人员
                break;
   //行政处理决定审批表
            case '行政处理决定审批表':
                this.com = this.resolver.resolveComponentFactory(Coms['DecisionApprovalFromComponent'] );
                caseHandler('casePerson') //取办案人员
                break;
   //案件审核表
            case '案件审核表':
                this.com = this.resolver.resolveComponentFactory(Coms['CaseReviewFormComponent'] );
                break;
  //案件调查终结报告
            case '案件调查终结报告':
                this.com = this.resolver.resolveComponentFactory(Coms['TerminationReportComponent'] );
                caseHandler('');
                break;
  //指定管辖通知书
            case '指定管辖通知书':
              this.com = this.resolver.resolveComponentFactory(Coms['JurusductionNoticeComponent'] );
              break;
  //《案件移送函》
            case '案件移送函':
              this.com = this.resolver.resolveComponentFactory(Coms['CaseTransferLetterComponent'] );
              break;
  
            case '案件交办通知书':
              this.com = this.resolver.resolveComponentFactory(Coms['CaseFilingNoticeComponent'] );
            break;
            case '涉嫌犯罪案件移送书':
              this.com = this.resolver.resolveComponentFactory(Coms['CriminalCaseTransferLetterComponent'] );
            break;
            case '协助调查函':
              this.com = this.resolver.resolveComponentFactory(Coms['InverstigationLetterComponent'] );
            break;
            case '协助扣押通知书':
              this.com = this.resolver.resolveComponentFactory(Coms['ArrestNoticeComponent'] );
            break;
  // other其他表 （新增  编辑）
            default:
              this.com = this.resolver.resolveComponentFactory(Coms['OtherComponent']);
               break;
          }
  // 新增编辑通用逻辑
          if (this.container && this.container.clear) {
            this.container.clear();
            this.comRef = this.container.createComponent(this.com); 
            this.comRef.instance.bizid = this.bizid;
  // 如果有docid（文书id）则为编辑
            if (docid) {
              this.comRef.instance.docid = docid;
              }
            }
          }
    },
    (err) => null,
    () => {
      // 取消当前订阅
      this.caseReview.getCreateCaseDoc().unsubscribe();
    },
  );
}

// 获取当前登陆人所属机构
getRegisterDepart(){
  let registerDepart =  JSON.parse(sessionStorage.getItem('organizations'))[0].orgName;
   return registerDepart;
}

// 通用新增修改逻辑
async customSave(){
  const formJson = (this.comRef.instance.formJson);
  const instance = this.comRef.instance;
    // 当前登录人所属机构
    formJson['registerDepart'] = this.getRegisterDepart();
    
    if(this.doctype == '立案审批表' || this.doctype == '不予立案审批表'){
      formJson.addressDetails = {
        city: instance.addressDetails[0],
        county: instance.addressDetails[1], 
        detail: instance.addressDetails[2]
      };
    }
    
    let submitObj: object = {
      filename: this.doctype + '.docx',
      stage: instance.getSelectValue,
      bizid: '' + this.bizid,
      doctype: this.doctype,
      formJson: JSON.stringify(formJson),
    };

    // 结案审批表
    if(this.doctype  == '结案审批表'){
      formJson.caseFiDate = moment(formJson.caseFiDate).format('YYYY-MM-DD');
      formJson.penDecDate = moment(formJson.penDecDate).format('YYYY-MM-DD');
    }

    // 行政处罚案件有关事项审批表 带有关联文书
    if(this.doctype == '行政处罚案件有关事项审批表'){
      if(instance.bizFileDoc){
        submitObj['relatedBizFile'] = {'docid':instance.bizFileDoc};
      }else{
        this.message.create('error','关联文书必选!!');
        return;
      }
    }
  
    // 修改  
    if (this.docid) {
      submitObj['docid'] = this.docid;
      this.caseDocService.bizfilePut(this.docid, JSON.stringify(formJson), instance.getSelectValue).subscribe((res)=>{
        this.updateCaseType(res)
      });
    } else {
    // 新增
      submitObj['bizid'] = this.bizid;  
      let code;
      if(this.doctype == '立案审批表' || this.doctype == '不予立案审批表'){
          code =   await this.caseservice.caseCodeGet().toPromise();
       }
      this.caseDocService.bizfilePost(submitObj).subscribe((bizdata:ReturnModel)=>{
        if(this.doctype == '立案审批表' || this.doctype == '不予立案审批表'){
          this.updateCaseType(bizdata,code.data);
        }else{
          this.callback(this.bizid)
          this.close();
        }
      });
    }
}




// 提交审批数据
submit():void{
  // 新增文书修改
  if (this.condition === 'New') {
    switch (this.doctype) {
    //  立案审批表     (新增  修改) 提交
    //  不予立案审批表  (新增  修改) 提交
        case '立案审批表':
        case '不予立案审批表':
        case '结案审批表':
        case '行政处罚案件有关事项审批表':
        case '行政处理决定审批表':
        case '案件审核表':
        case '案件调查终结报告':
        case '指定管辖通知书':
        case '案件移送函':
        case '案件交办通知书':  
        case '涉嫌犯罪案件移送书':
        case '协助调查函':  
        case '协助扣押通知书':
            {
              this.customSave();
            }
        break;
      default:
        break;
    }
  // 审批提交逻辑
  } else if (this.condition === 'Approval') {
    if(this.comRef.instance&&this.comRef.instance.BizFile){
      // 审批模块参数处理
    let caseValue:any = this.caseModule.filter((val:any)=>{
      return  val.approvaltype  == this.approvalModule.caseModuleValue;
      })
    let templatesimg = JSON.parse(caseValue[0].templatesimg);
    const {caseradioValue, caseModuleValue, ideaValue, date} = this.approvalModule;
    
    if (date) {
      const dateString = (moment(date).format('YYYY-MM-DD hh:mm:ss'));
      const year = dateString.substring(0, 4);
      const month = dateString.substring(5, 7);
      const day = dateString.substring(8, 10);
      const hours = dateString.substring(11, 13);
      const minutes = dateString.substring(14, 16);
      this.approvalModule.date = (moment(date).format('YYYY-MM-DD hh:mm:ss'));
      this.formJson[templatesimg.year] = year;
      this.formJson[templatesimg.month] = month;
      this.formJson[templatesimg.day] = day;
    } 
    // 审批模块内容 
    let approveJson = Object.assign({},
      {
        [templatesimg.opinion]:ideaValue,
        [templatesimg.approver]:sessionStorage.getItem('realName')
      },{
        [templatesimg.year]:this.formJson[templatesimg.year],
        [templatesimg.month]:this.formJson[templatesimg.month],
        [templatesimg.day]:this.formJson[templatesimg.day],
      })
    switch (this.doctype) {
      // 立案审批表     （审批 提交）
      // 不予立案审批表 （审批 提交）
      case '立案审批表':
      case '不予立案审批表':
        {
          const obj = Object.assign({}, this.comRef.instance.formJson, approveJson);
          const  approvalObj = Object.assign({}, this.approvalModule, {approvePerson: sessionStorage.getItem('realName')});
          let approve: any = {
            registerPerson: this.approvalArr[2]['data']['partyName'],
            registerNumber: this.approvalArr[2]['data']['code'],
            approveInfo: JSON.stringify(approvalObj),
          };
          // 判断是否为驳回 (value为2  如果为驳回则不提交审批模块)
          if (caseradioValue == '2') {approve = ''; }
          // 调用文书保存服务 
          this.caseDocService.saveApprove(this.docid, JSON.stringify(approve), JSON.stringify(obj)).subscribe((data:any) => {
            this.callback(this.bizid);
            if(data.code  == "4"){
                this.message.create('success', `审批成功`);
                this.updateApprovalDocInfo();
            }else{
              this.message.create('error', data.message);
            }
          });
        } break; 
    // 案件来源登记表  （审批  提交）
      case '案件来源登记表': {
      this.formJson[templatesimg.opinion] = ideaValue;
      this.formJson[templatesimg.approver] = sessionStorage.getItem('realName');
      const approvalObj = Object.assign({}, this.approvalModule, {approvePerson: sessionStorage.getItem('realName')});
        let approve: any = {
          registerPerson: this.formJson.registerPerson,
          registerNumber: this.formJson.registerNumber,
          approveInfo: JSON.stringify(approvalObj),
        };
      // 判断是否为驳回 (value为2  如果为驳回则不提交审批模块)
        if (caseradioValue == '2') {approve = '';}
        this.caseDocService.saveApprove(this.docid, JSON.stringify(approve),JSON.stringify(this.formJson)).subscribe((data:any) => {
          if(data.code  == "4"){
            this.message.create('success', `审批成功`);
            this.updateApprovalDocInfo();

          }else{
            this.message.create('error', data.message);
          }
        });
    } break;
    case '结案审批表':
        const obj = Object.assign({}, this.comRef.instance.formJson, approveJson);
        const approvalObj = Object.assign({}, this.approvalModule, {approvePerson: sessionStorage.getItem('realName')});

        let approve: any = {
          approveInfo: JSON.stringify(approvalObj),
        };
      // 判断是否为驳回 (value为2  如果为驳回则不提交审批模块)
        if (caseradioValue === '2') {approve = '';}
        this.caseDocService.saveApprove(this.docid, JSON.stringify(approve),JSON.stringify(obj)).subscribe((data:any) => {
          if(data.code  == "4"){
            this.message.create('success', `审批成功`);
            this.updateApprovalDocInfo();

          }else{
            this.message.create('error', data.message);

          }
        });
    break;
    case '行政处罚案件有关事项审批表':{
      const obj = Object.assign({}, this.comRef.instance.formJson, approveJson);
      const approvalObj = Object.assign({}, this.approvalModule, {approvePerson: sessionStorage.getItem('realName')});

      let approve: any = {
        approveInfo: JSON.stringify(approvalObj),
      };
    // 判断是否为驳回 (value为2  如果为驳回则不提交审批模块)
      if (caseradioValue === '2') {approve = '';}
      this.caseDocService.saveApprove(this.docid, JSON.stringify(approve),JSON.stringify(obj)).subscribe((data:any) => {
        if(data.code  == "4"){
          this.message.create('success', `审批成功`);          
          this.updateApprovalDocInfo();
        }else{
          this.message.create('error', data.message);
        }
      });
    }
       
    break;
    case '行政处理决定审批表':
      {
        const obj = Object.assign({}, this.comRef.instance.formJson, approveJson);
        const approvalObj = Object.assign({}, this.approvalModule, {approvePerson: sessionStorage.getItem('realName')});

        let approve: any = {
          approveInfo: JSON.stringify(approvalObj),
        };
      // 判断是否为驳回 (value为2  如果为驳回则不提交审批模块)
        if (caseradioValue === '2') {approve = '';}
        this.caseDocService.saveApprove(this.docid, JSON.stringify(approve),JSON.stringify(obj)).subscribe((data:any) => {
          if(data.code  == "4"){
            this.message.create('success', `审批成功`);
            this.updateApprovalDocInfo();
          }else{
            this.message.create('error', data.message);
          }
        });
      }
       
    break;
    case '案件审核表':
        {
          const obj = Object.assign({}, this.comRef.instance.formJson, approveJson);
          const approvalObj = Object.assign({}, this.approvalModule, {approvePerson: sessionStorage.getItem('realName')});
  
          let approve: any = {
            approveInfo: JSON.stringify(approvalObj),
          };
        // 判断是否为驳回 (value为2  如果为驳回则不提交审批模块)
          if (caseradioValue === '2') {approve = '';}
          this.caseDocService.saveApprove(this.docid, JSON.stringify(approve),JSON.stringify(obj)).subscribe((data:any) => {
            if(data.code  == "4"){
              this.message.create('success', `审批成功`);     
              this.updateApprovalDocInfo();
            }else{
              this.message.create('error', data.message); 
            }
          });
        }
      break;
      case '案件调查终结报告':
        {
          const obj = Object.assign({}, this.comRef.instance.formJson, approveJson);
          const approvalObj = Object.assign({}, this.approvalModule, {approvePerson: sessionStorage.getItem('realName')});
  
          let approve: any = {
            approveInfo: JSON.stringify(approvalObj),
          };
        // 判断是否为驳回 (value为2  如果为驳回则不提交审批模块)
      
          if (caseradioValue === '2') {approve = '';}
          this.caseDocService.saveApprove(this.docid, JSON.stringify(approve),JSON.stringify(obj)).subscribe((data:any) => {
            if(data.code  == "4"){
              this.message.create('success', `审批成功`);
              this.updateApprovalDocInfo();
            }else{
              this.message.create('error',data.message);
            }
          });
        }
      break;
      case '协助调查函':
        {
          const obj = Object.assign({}, this.comRef.instance.formJson, approveJson);
          const approvalObj = Object.assign({}, this.approvalModule, {approvePerson: sessionStorage.getItem('realName')});
  
          let approve: any = {
            approveInfo: JSON.stringify(approvalObj),
          };
        // 判断是否为驳回 (value为2  如果为驳回则不提交审批模块)
      
          if (caseradioValue === '2') {approve = '';}
          this.caseDocService.saveApprove(this.docid, JSON.stringify(approve),JSON.stringify(obj)).subscribe((data:any) => {
            if(data.code  == "4"){
              this.message.create('success', `审批成功`);
              this.updateApprovalDocInfo();
            }else{
              this.message.create('error', data.message);
            }
          });
        }
      break;
      case '协助扣押通知书':
        {
          const obj = Object.assign({}, this.comRef.instance.formJson, approveJson);
          const approvalObj = Object.assign({}, this.approvalModule, {approvePerson: sessionStorage.getItem('realName')});
  
          let approve: any = {
            approveInfo: JSON.stringify(approvalObj),
          };
        // 判断是否为驳回 (value为2  如果为驳回则不提交审批模块)
      
          if (caseradioValue === '2') {approve = '';}
          this.caseDocService.saveApprove(this.docid, JSON.stringify(approve),JSON.stringify(obj)).subscribe((data:any) => {
            if(data.code  == "4"){
              this.message.create('success', `审批成功`);
              this.updateApprovalDocInfo();
            }else{
              this.message.create('error', data.message);

            }
          });
        }
      break;
      default:
        break;
    }
    } 
  }
}

  // 关闭弹窗
  close():void{
    this.caseReview.showWindow = false;
  }



  // 案件选择信息
  caseRadioChange(event) {
    switch (event) {
      case '0':this.approvalModule.ideaValue = this.approvalModule.caseradioName ='同意';break;
      case '1': this.approvalModule.ideaValue = this.approvalModule.caseradioName ='不同意';break;
      case '2': this.approvalModule.ideaValue = this.approvalModule.caseradioName = '驳回';break;
      default:break;
    }
  }


// 每次服务调用更新type
updateCaseType(bizData:any,code?:string):void {
  if (bizData.code == 4) {
    // 调用更新type
    this.caseservice.caseDocPut(
      this.bizid,
      null,
      this.comRef.instance.treeValue,
      this.maxType([].concat(this.caseReview.cloneBizfile,this.caseReview.cloneEvidence)),
      !this.docid?this.dateFormat(this.comRef.instance.agentDate,'yyyy-MM-dd'):null,
      code?code:null
      ).subscribe((res) => {
        console.log(res)
        this.callback(this.bizid);
        this.message.create('success', `提交成功`);
        this.close();
    });
  }
}

// 每次审批提交调用插入信息
updateApprovalDocInfo():void {   
  // 调用服务将审批成功info提交
  this.caseservice.caseDocPut(this.bizid, this.approvalModule.ideaValue).subscribe((data) => {
    this.callback(this.bizid);
    this.close();
  },err=>{
    this.message.create('error', `提交失败`);
    this.close();
  });
}

  // 查询元素
findElement(parent: any, classname:string): any[] {
  const result: any = [];
  const next = (parentChild) => {
    for (let i = 0; i < parentChild.children.length; i++) {
      if (parentChild.children[i].className === classname) {
        result.push(parentChild.children[i]);
      } else {
        next(parentChild.children[i]);
      }
    }
  };
  next(parent);
  return result;
}

// Date 格式化
dateFormat (date:Date,fmt:string) :string { //author: meizz 
  let formatDate:Date = new Date(date);
  var o = {
      "M+": formatDate.getMonth() + 1, //月份 
      "d+": formatDate.getDate(), //日 
      "h+": formatDate.getHours(), //小时 
      "m+": formatDate.getMinutes(), //分 
      "s+": formatDate.getSeconds(), //秒 
      "q+": Math.floor((formatDate.getMonth() + 3) / 3), //季度 
      "S": formatDate.getMilliseconds() //毫秒 
  };
  if (/(y+)/.test(fmt)) fmt = fmt.replace(RegExp.$1, (formatDate.getFullYear() + "").substr(4 - RegExp.$1.length));
  for (var k in o)
  if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
  return fmt;
}

// 获取最大案件类型
maxType(arr:any) :string{
  let max;
  const CaseTypes:any[] = [];
  CaseTypes['线索'] = 1;
  CaseTypes['线索核查'] = 1;
  CaseTypes['立案'] = 2;
  CaseTypes['调查取证'] = 3;
  CaseTypes['处罚决定'] = 4;
  CaseTypes['执行与结案'] = 5;
  CaseTypes['强制执行'] = 6;
  arr.forEach(item => {
    let key = item.stage?item.stage:item.filingLink;
    if(max){
      if(CaseTypes[key] > CaseTypes[max]){
        max = key
      }
    } else {
        max = key
    }
  });
  return max
}
}
